import Vue from 'vue'
import VueRouter from 'vue-router'
import message from "@/api/common/message.js"
import * as API from "@api/common/common";
Vue.use(VueRouter)


//不同页面路由配置文件 引入
import * as pubApi from '@api/public'

import equipment from './equipment'
import userControl from './userControl'
import system from './system'
import shop from './shop'
import operate from './operate'
import finance from './finance'
import banner from './banner'
import order from './order'


const router = new VueRouter({
    routes: [{
            path: '/',
            name: 'login',
            component: resolve => require(['@/views/login'], resolve),
            redirect: '/login',
        },
        {
            path: '/login',
            name: '登录',
            component: resolve => require(['@/views/login'], resolve),
        },
        {
            path: '/index',
            name: '首页',
            component: resolve => require(['@/views/home'], resolve),
        },
        ...equipment,
        ...userControl,
        ...system,
        ...shop,
        ...operate,
        ...finance,
        ...banner,
        ...order
    ]
})

function getRoot(){
  API.get("/v1/flash/permissions/user").then(res=>{
        let array =[]
        if(res.IsPositive){
            res.Data.records.forEach(element => {
              array.push(element.id)
            });
            localStorage.setItem("Rootarray",array)
        }
  })
}


router.beforeEach((to, from, next) => {
      let token = pubApi.getCookie("uKey")
      if (token!=undefined && token!="") {    // 判断本地是否存在token
        getRoot()
        if(to.path === '/login'){
              router.push({path:"/index"})
              next()
              return
        }
        if(to.meta.id!=undefined){
          let Rootarray=localStorage.getItem("Rootarray")==undefined?'':localStorage.getItem("Rootarray").split(",")
          if(Rootarray.indexOf(to.meta.id)==-1){
              message.message.openWarning("此账号没有当前页面操作权限",'warning')
              router.push({path:"/index"})
              return
           }
     }
        next()
      } else {
        // 未登录,跳转到登陆页面,防止死循环这里
        if (to.path === '/login') {
            next();
            return
        }
       next({path: '/login'})
    }
  });

// 解决重复点击导航路由报错
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err);
}

export default router